<template>
  <div class="merchant-management">
    <div class="page-header">
      <h2>商家管理</h2>
      <el-button type="primary" @click="handleAdd">
        <i class="fas fa-plus"></i> 新增商家
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商家名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入商家名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="联系人">
          <el-input
            v-model="searchForm.contact"
            placeholder="请输入联系人"
            clearable
          />
        </el-form-item>
        <el-form-item label="商家类型">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择商家类型"
            clearable
          >
            <el-option label="酒店" value="hotel" />
            <el-option label="景点" value="scenic" />
            <el-option label="文创商家" value="cultural" />
            <el-option label="餐饮" value="food" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <i class="fas fa-search"></i> 搜索
          </el-button>
          <el-button @click="resetSearch">
            <i class="fas fa-redo"></i> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商家列表 -->
    <el-card class="list-card">
      <el-table
        :data="sortedMerchantList"
        style="width: 100%"
        v-loading="loading"
        border
        @sort-change="handleSortChange"
      >
        <el-table-column prop="id" label="ID" width="80" sortable="custom" />
        <el-table-column
          prop="name"
          label="商家名称"
          min-width="150"
          sortable="custom"
        >
          <template #default="scope">
            <div class="merchant-info">
              <el-avatar :size="40" :src="scope.row.logo" />
              <span class="merchant-name">{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="type"
          label="商家类型"
          width="100"
          sortable="custom"
        >
          <template #default="scope">
            <el-tag :type="getMerchantTypeTag(scope.row.type)">
              {{ getMerchantTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="contact" label="联系人" width="100" />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column prop="address" label="地址" min-width="200" />
        <el-table-column
          prop="status"
          label="状态"
          width="100"
          sortable="custom"
        >
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="入驻时间"
          width="180"
          sortable="custom"
        />
        <el-table-column label="操作" fixed="right" width="250">
          <template #default="scope">
            <el-button-group>
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
              >
                <i class="fas fa-edit"></i> 编辑
              </el-button>
              <el-button
                type="info"
                size="small"
                @click="showDetail(scope.row)"
              >
                <i class="fas fa-eye"></i> 详情
              </el-button>
              <el-button
                type="success"
                size="small"
                @click="handleAudit(scope.row)"
                v-if="scope.row.status === 'pending'"
              >
                <i class="fas fa-check"></i> 审核
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope.row)"
              >
                <i class="fas fa-trash"></i> 删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
        
        <template #empty>
          <div class="empty-state">
            <el-empty 
              description="暂无商家数据" 
              :image-size="200"
            >
              <div class="empty-text">还没有添加任何商家信息</div>
              <div class="empty-subtext">添加商家信息开始管理您的合作伙伴</div>
              <el-button type="primary" @click="handleAdd" class="mt-4">添加第一个商家</el-button>
            </el-empty>
          </div>
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 商家编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增商家' : '编辑商家'"
      width="800px"
      :append-to-body="true"
      :modal-class="'merchant-edit-modal'"
      :lock-scroll="true"
      destroy-on-close
    >
      <el-scrollbar height="calc(90vh - 200px)">
        <el-form
          ref="merchantFormRef"
          :model="merchantForm"
          :rules="merchantFormRules"
          label-width="120px"
          class="merchant-form"
        >
          <!-- 基本信息 -->
          <div class="form-section">
            <h4 class="section-title">基本信息</h4>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="商家名称" prop="name">
                  <el-input
                    v-model="merchantForm.name"
                    placeholder="请输入商家名称"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商家类型" prop="type">
                  <el-select
                    v-model="merchantForm.type"
                    placeholder="请选择商家类型"
                  >
                    <el-option label="酒店" value="hotel" />
                    <el-option label="景点" value="scenic" />
                    <el-option label="文创商家" value="cultural" />
                    <el-option label="餐饮" value="food" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系人" prop="contact">
                  <el-input
                    v-model="merchantForm.contact"
                    placeholder="请输入联系人"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="phone">
                  <el-input
                    v-model="merchantForm.phone"
                    placeholder="请输入联系电话"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="商家地址" prop="address">
              <el-input
                v-model="merchantForm.address"
                placeholder="请输入商家地址"
              />
            </el-form-item>

            <el-form-item label="商家简介" prop="description">
              <el-input
                type="textarea"
                v-model="merchantForm.description"
                :rows="3"
                placeholder="请输入商家简介"
              />
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="商家Logo" prop="logo">
                  <el-upload
                    class="avatar-uploader"
                    action="/api/upload"
                    :show-file-list="false"
                    :on-success="handleLogoSuccess"
                    :before-upload="beforeLogoUpload"
                  >
                    <img
                      v-if="merchantForm.logo"
                      :src="merchantForm.logo"
                      class="avatar"
                    />
                    <el-icon v-else class="avatar-uploader-icon">
                      <i class="fas fa-plus"></i>
                    </el-icon>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 营业信息 -->
          <div class="form-section">
            <h4 class="section-title">营业信息</h4>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="营业时间" prop="businessHours">
                  <el-time-picker
                    v-model="merchantForm.businessHours[0]"
                    placeholder="开始时间"
                    format="HH:mm"
                    :default-time="new Date(2000, 1, 1, 9, 0)"
                  />
                  <span class="time-separator">至</span>
                  <el-time-picker
                    v-model="merchantForm.businessHours[1]"
                    placeholder="结束时间"
                    format="HH:mm"
                    :default-time="new Date(2000, 1, 1, 18, 0)"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商家标签" prop="tags">
                  <el-select
                    v-model="merchantForm.tags"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    placeholder="请选择或输入标签"
                  >
                    <el-option
                      v-for="tag in tagOptions"
                      :key="tag"
                      :label="tag"
                      :value="tag"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 资质信息 -->
          <div class="form-section">
            <h4 class="section-title">资质信息</h4>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="法人姓名" prop="legalPerson">
                  <el-input
                    v-model="merchantForm.legalPerson"
                    placeholder="请输入法人姓名"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证号" prop="idCard">
                  <el-input
                    v-model="merchantForm.idCard"
                    placeholder="请输入身份证号"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="营业执照" prop="license">
              <el-upload
                class="license-uploader"
                action="/api/upload"
                :show-file-list="false"
                :on-success="handleLicenseSuccess"
                :before-upload="beforeLicenseUpload"
              >
                <img
                  v-if="merchantForm.license"
                  :src="merchantForm.license"
                  class="license"
                />
                <el-icon v-else class="license-uploader-icon">
                  <i class="fas fa-plus"></i>
                </el-icon>
              </el-upload>
            </el-form-item>

            <el-form-item label="其他资质" prop="qualifications">
              <el-upload
                class="qualification-uploader"
                action="/api/upload"
                list-type="picture-card"
                :file-list="merchantForm.qualifications"
                :on-success="handleQualificationSuccess"
                :before-upload="beforeQualificationUpload"
                :on-remove="handleQualificationRemove"
              >
                <i class="fas fa-plus"></i>
              </el-upload>
            </el-form-item>
          </div>

          <!-- 结算信息 -->
          <div class="form-section">
            <h4 class="section-title">结算信息</h4>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="开户银行" prop="bankName">
                  <el-input
                    v-model="merchantForm.bankName"
                    placeholder="请输入开户银行"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="银行账号" prop="bankAccount">
                  <el-input
                    v-model="merchantForm.bankAccount"
                    placeholder="请输入银行账号"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      title="商家审核"
      width="460px"
      :modal-class="'audit-dialog'"
      destroy-on-close
      align-center
    >
      <div class="audit-content">
        <div class="merchant-info mb-4 text-center">
          <el-avatar :size="64" :src="currentMerchant.logo" class="mb-2" />
          <h3 class="text-lg font-medium">{{ currentMerchant.name }}</h3>
          <p class="text-gray-500 text-sm">
            {{ getMerchantTypeLabel(currentMerchant.type) }}
          </p>
        </div>

        <div class="audit-options">
          <el-radio-group v-model="auditForm.status" class="audit-radio-group">
            <el-radio-button label="approved">
              <div class="audit-option">
                <el-icon class="audit-icon success"><Check /></el-icon>
                <span>通过审核</span>
              </div>
            </el-radio-button>
            <el-radio-button label="rejected">
              <div class="audit-option">
                <el-icon class="audit-icon danger"><Close /></el-icon>
                <span>拒绝通过</span>
              </div>
            </el-radio-button>
          </el-radio-group>
        </div>

        <div class="mt-4" v-if="auditForm.status === 'rejected'">
          <el-input
            v-model="auditForm.comment"
            type="textarea"
            :rows="3"
            placeholder="请输入拒绝原因（必填）"
          />
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleAuditSubmit"
            :disabled="isSubmitDisabled"
          >
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 商家详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="商家详情"
      width="800px"
      :append-to-body="true"
      :modal-class="'merchant-detail-modal'"
      :lock-scroll="true"
      destroy-on-close
    >
      <el-scrollbar height="calc(90vh - 200px)">
        <div class="merchant-detail">
          <!-- 基本信息 -->
          <div class="detail-section">
            <h4 class="section-title">基本信息</h4>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="商家名称">{{
                currentMerchant.name
              }}</el-descriptions-item>
              <el-descriptions-item label="商家类型">
                <el-tag :type="getMerchantTypeTag(currentMerchant.type)">
                  {{ getMerchantTypeLabel(currentMerchant.type) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="联系人">{{
                currentMerchant.contact
              }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{
                currentMerchant.phone
              }}</el-descriptions-item>
              <el-descriptions-item label="商家地址" :span="2">{{
                currentMerchant.address
              }}</el-descriptions-item>
              <el-descriptions-item label="入驻时间">{{
                currentMerchant.createTime
              }}</el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="getStatusType(currentMerchant.status)">
                  {{ getStatusLabel(currentMerchant.status) }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 商家资质 -->
          <div class="detail-section">
            <h4 class="section-title">商家资质</h4>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="法人姓名">{{
                currentMerchant.legalPerson
              }}</el-descriptions-item>
              <el-descriptions-item label="身份证号">{{
                currentMerchant.idCard
              }}</el-descriptions-item>
              <el-descriptions-item label="营业执照">
                <el-image
                  v-if="currentMerchant.license"
                  :src="currentMerchant.license"
                  fit="cover"
                  class="license-image"
                  @click="handlePreviewImage(currentMerchant.license)"
                />
              </el-descriptions-item>
              <el-descriptions-item label="其他资质">
                <el-image
                  v-for="(img, index) in currentMerchant.qualifications"
                  :key="index"
                  :src="img"
                  fit="cover"
                  class="qualification-image"
                  @click="handlePreviewImage(img)"
                />
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 经营信息 -->
          <div class="detail-section">
            <h4 class="section-title">经营信息</h4>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="营业时间"
                >{{ currentMerchant.businessHours?.[0] }} -
                {{ currentMerchant.businessHours?.[1] }}</el-descriptions-item
              >
              <el-descriptions-item label="商家标签">
                <el-tag
                  v-for="tag in currentMerchant.tags"
                  :key="tag"
                  class="mx-1"
                >
                  {{ tag }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="商家简介" :span="2">{{
                currentMerchant.description
              }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 结算信息 -->
          <div class="detail-section">
            <h4 class="section-title">结算信息</h4>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="开户银行">{{
                currentMerchant.bankName
              }}</el-descriptions-item>
              <el-descriptions-item label="银行账号">{{
                currentMerchant.bankAccount
              }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleEdit(currentMerchant)"
            >编辑</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="previewVisible"
      :url-list="[previewUrl]"
      @close="previewVisible = false"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { Check, Close } from "@element-plus/icons-vue";
import service from "@/api/axios";

const router = useRouter();

// 搜索表单
const searchForm = reactive({
  name: "",
  contact: "",
  type: "",
  status: "",
});

// 商家列表数据
const merchantList = ref([
  {
    id: 1,
    name: "贵港大酒店",
    type: "hotel",
    contact: "张经理",
    phone: "13800138000",
    address: "广西贵港市港北区中山路128号",
    description: "贵港市中心地段的四星级酒店，环境优雅，设施完善",
    status: "approved",
    createTime: "2024-03-01 10:00:00",
    logo: "https://example.com/logo1.png",
    businessHours: [new Date(2000, 1, 1, 8, 0), new Date(2000, 1, 1, 22, 0)],
    tags: ["商务酒店", "会议服务", "餐饮"],
    legalPerson: "张三",
    idCard: "450800198001011234",
    license: "https://example.com/license1.jpg",
    bankName: "中国工商银行贵港支行",
    bankAccount: "6222021234567890123",
    qualifications: [
      { name: "卫生许可证.jpg", url: "https://example.com/qual1.jpg" },
      { name: "消防安全证.jpg", url: "https://example.com/qual2.jpg" },
    ],
  },
  {
    id: 2,
    name: "江滨公园景区",
    type: "scenic",
    contact: "李经理",
    phone: "13800138001",
    address: "广西贵港市港北区江滨路1号",
    description: "贵港市著名的滨江景区，风景优美，设施齐全",
    status: "approved",
    createTime: "2024-03-01 11:00:00",
    logo: "https://example.com/logo2.png",
    businessHours: [new Date(2000, 1, 1, 7, 30), new Date(2000, 1, 1, 19, 30)],
    tags: ["自然景观", "亲子游玩", "摄影基地"],
    legalPerson: "李四",
    idCard: "450800198203023456",
    license: "https://example.com/license2.jpg",
    bankName: "中国建设银行贵港分行",
    bankAccount: "6227002345678901234",
    qualifications: [
      { name: "景区等级证书.jpg", url: "https://example.com/qual3.jpg" },
    ],
  },
  {
    id: 3,
    name: "荷塘月色餐厅",
    type: "food",
    contact: "王店长",
    phone: "13800138002",
    address: "广西贵港市港北区荷城路56号",
    description: "特色粤式餐厅，以荷叶粉、荷叶鸡等地方特色菜品著称",
    status: "pending",
    createTime: "2024-03-02 09:30:00",
    logo: "https://example.com/logo3.png",
    businessHours: [new Date(2000, 1, 1, 10, 0), new Date(2000, 1, 1, 21, 30)],
    tags: ["粤式料理", "地方特色", "商务宴请"],
    legalPerson: "王五",
    idCard: "450800198405045678",
    license: "https://example.com/license3.jpg",
    bankName: "中国农业银行贵港支行",
    bankAccount: "6228003456789012345",
    qualifications: [
      { name: "食品经营许可证.jpg", url: "https://example.com/qual4.jpg" },
      { name: "餐饮服务许可证.jpg", url: "https://example.com/qual5.jpg" },
    ],
  },
  {
    id: 4,
    name: "贵港文创馆",
    type: "cultural",
    contact: "赵馆长",
    phone: "13800138003",
    address: "广西贵港市港北区文化路88号",
    description: "展示和销售贵港特色文创产品，推广本地文化艺术",
    status: "approved",
    createTime: "2024-03-02 14:00:00",
    logo: "https://example.com/logo4.png",
    businessHours: [new Date(2000, 1, 1, 9, 30), new Date(2000, 1, 1, 18, 0)],
    tags: ["文创产品", "非遗展示", "文化体验"],
    legalPerson: "赵六",
    idCard: "450800198607067890",
    license: "https://example.com/license4.jpg",
    bankName: "中国银行贵港分行",
    bankAccount: "6216004567890123456",
    qualifications: [
      { name: "营业执照.jpg", url: "https://example.com/qual6.jpg" },
    ],
  },
  {
    id: 5,
    name: "桂香茶馆",
    type: "food",
    contact: "陈经理",
    phone: "13800138004",
    address: "广西贵港市港北区茶城路23号",
    description: "传统茶馆，提供各类特色茶点和地方小吃",
    status: "rejected",
    createTime: "2024-03-03 11:20:00",
    logo: "https://example.com/logo5.png",
    businessHours: [new Date(2000, 1, 1, 8, 30), new Date(2000, 1, 1, 22, 30)],
    tags: ["茶文化", "传统小吃", "休闲娱乐"],
    legalPerson: "陈七",
    idCard: "450800198809098765",
    license: "https://example.com/license5.jpg",
    bankName: "交通银行贵港支行",
    bankAccount: "6222005678901234567",
    qualifications: [
      { name: "食品安全证.jpg", url: "https://example.com/qual7.jpg" },
    ],
  },
]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);
const loading = ref(false);

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref("add");
const merchantFormRef = ref(null);
const merchantForm = reactive({
  name: "",
  type: "",
  contact: "",
  phone: "",
  address: "",
  description: "",
  logo: "",
  license: "",
  businessHours: [new Date(2000, 1, 1, 9, 0), new Date(2000, 1, 1, 18, 0)],
  tags: [],
  legalPerson: "",
  idCard: "",
  bankName: "",
  bankAccount: "",
  qualifications: [],
});

// 审核对话框相关
const auditDialogVisible = ref(false);
const auditFormRef = ref(null);
const auditForm = reactive({
  status: "approved",
  comment: "",
});

// 表单验证规则
const merchantFormRules = {
  name: [{ required: true, message: "请输入商家名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择商家类型", trigger: "change" }],
  contact: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  address: [{ required: true, message: "请输入商家地址", trigger: "blur" }],
};

const auditFormRules = {
  status: [{ required: true, message: "请选择审核结果", trigger: "change" }],
  comment: [{ required: true, message: "请输入拒绝原因", trigger: "blur" }],
};

// 商家类型标签
const getMerchantTypeTag = (type) => {
  const typeMap = {
    hotel: "",
    scenic: "success",
    cultural: "warning",
    food: "danger",
  };
  return typeMap[type] || "info";
};

const getMerchantTypeLabel = (type) => {
  const typeMap = {
    hotel: "酒店",
    scenic: "景点",
    cultural: "文创商家",
    food: "餐饮",
  };
  return typeMap[type] || "未知";
};

// 状态标签
const getStatusType = (status) => {
  const statusMap = {
    pending: "warning",
    approved: "success",
    rejected: "danger",
  };
  return statusMap[status] || "info";
};

const getStatusLabel = (status) => {
  const statusMap = {
    pending: "待审核",
    approved: "已通过",
    rejected: "已拒绝",
  };
  return statusMap[status] || "未知";
};

// 搜索处理
const handleSearch = () => {
  loading.value = true;
  
  const params = {};
  if (searchForm.name) params.name = searchForm.name;
  if (searchForm.contact) params.contact = searchForm.contact;
  if (searchForm.type) params.type = searchForm.type;
  if (searchForm.status) params.status = searchForm.status;
  
  fetchMerchantList(params);
};

// 获取商家列表数据
const fetchMerchantList = async (params = {}) => {
  loading.value = true;
  
  try {
    const response = await service.get('/admin/merchants', { params });
    
    if (response.code === 200) {
      // 将API返回的字段映射到前端需要的字段
      merchantList.value = (response.data.list || []).map(item => ({
        id: item.id,
        name: item.storeName,
        type: item.merchantType,
        contact: item.legalPerson,
        phone: item.phone,
        address: item.address,
        description: item.description,
        status: item.status,
        createTime: item.createTime,
        logo: item.avatar,
        businessHours: item.businessHours,
        tags: item.tags,
        legalPerson: item.legalPerson,
        idCard: item.idCard,
        license: item.licenseUrl,
        bankName: item.bankName,
        bankAccount: item.bankAccount,
        qualifications: []
      }));
      total.value = response.data.total || 0;
    } else {
      // 使用测试数据
      console.log("使用测试数据");
      total.value = merchantList.value.length;
    }
  } catch (error) {
    console.error("获取商家列表失败:", error);
    ElMessage.error("获取商家列表失败");
  } finally {
    loading.value = false;
  }
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  handleSearch();
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  handleSearch();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  handleSearch();
};

// 新增商家
const handleAdd = () => {
  dialogType.value = "add";
  Object.keys(merchantForm).forEach((key) => {
    merchantForm[key] = "";
  });
  dialogVisible.value = true;
};

// 编辑商家
const handleEdit = (row) => {
  dialogType.value = "edit";
  Object.assign(merchantForm, {
    id: row.id,
    name: row.name,
    type: row.type,
    contact: row.contact,
    phone: row.phone,
    address: row.address,
    description: row.description,
    logo: row.logo,
    license: row.license,
    businessHours: row.businessHours || [
      new Date(2000, 1, 1, 9, 0),
      new Date(2000, 1, 1, 18, 0),
    ],
    tags: row.tags || [],
    legalPerson: row.legalPerson,
    idCard: row.idCard,
    bankName: row.bankName,
    bankAccount: row.bankAccount,
    qualifications: row.qualifications || [],
  });
  if (detailVisible.value) {
    detailVisible.value = false;
  }
  dialogVisible.value = true;
};

// 删除商家
const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该商家吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const response = await service.delete(`/admin/merchants/${row.id}`);
        
        if (response.code === 200) {
          ElMessage.success("删除成功");
          handleSearch();
        } else {
          ElMessage.error(response.message || "删除失败");
        }
      } catch (error) {
        console.error("删除商家失败:", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {});
};

// 审核商家
const handleAudit = (row) => {
  currentMerchant.value = row;
  auditForm.status = "approved";
  auditForm.comment = "";
  auditDialogVisible.value = true;
};

// 提交审核
const handleAuditSubmit = async () => {
  if (!currentMerchant.value) return;
  
  // 验证表单
  if (auditForm.status === "rejected" && !auditForm.comment) {
    ElMessage.warning("拒绝时必须填写原因");
    return;
  }
  
  try {
    const response = await service.post(`/admin/merchants/${currentMerchant.value.id}/audit`, {
      status: auditForm.status,
      comment: auditForm.comment
    });
    
    if (response.code === 200) {
      ElMessage.success("审核提交成功");
      auditDialogVisible.value = false;
      handleSearch();
    } else {
      ElMessage.error(response.message || "审核提交失败");
    }
  } catch (error) {
    console.error("审核提交失败:", error);
    ElMessage.error("审核提交失败");
  }
};

// Logo上传
const handleLogoSuccess = (res, file) => {
  merchantForm.logo = URL.createObjectURL(file.raw);
};

const beforeLogoUpload = (file) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error("上传头像图片只能是 JPG 或 PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 营业执照上传
const handleLicenseSuccess = (res, file) => {
  merchantForm.license = URL.createObjectURL(file.raw);
};

const beforeLicenseUpload = (file) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isJPG && !isPNG) {
    ElMessage.error("上传营业执照只能是 JPG 或 PNG 格式!");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("上传营业执照大小不能超过 5MB!");
    return false;
  }
  return true;
};

// 提交表单
const handleSubmit = async () => {
  if (!merchantFormRef.value) return;

  await merchantFormRef.value.validate((valid, fields) => {
    if (valid) {
      // TODO: 调用保存API
      ElMessage.success(dialogType.value === "add" ? "添加成功" : "更新成功");
      dialogVisible.value = false;
      handleSearch();
    }
  });
};

// 排序配置
const sortConfig = reactive({
  prop: "createTime",
  order: "descending",
});

// 获取排序后的数据
const sortedMerchantList = computed(() => {
  const list = [...merchantList.value];
  if (!sortConfig.prop) return list;

  return list.sort((a, b) => {
    let aValue = a[sortConfig.prop];
    let bValue = b[sortConfig.prop];

    // 处理时间排序
    if (sortConfig.prop === "createTime") {
      aValue = new Date(aValue).getTime();
      bValue = new Date(bValue).getTime();
    }

    if (sortConfig.order === "ascending") {
      return aValue > bValue ? 1 : -1;
    } else {
      return aValue < bValue ? 1 : -1;
    }
  });
});

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  sortConfig.prop = prop;
  sortConfig.order = order;
  handleSearch();
};

// 详情相关
const detailVisible = ref(false);
const currentMerchant = reactive({});
const previewVisible = ref(false);
const previewUrl = ref("");

// 显示商家详情
const showDetail = (row) => {
  Object.assign(currentMerchant, row);
  detailVisible.value = true;
};

// 图片预览
const handlePreviewImage = (url) => {
  previewUrl.value = url;
  previewVisible.value = true;
};

// 计算属性：判断提交按钮是否禁用
const isSubmitDisabled = computed(() => {
  if (auditForm.status === "rejected" && !auditForm.comment) {
    return true;
  }
  return false;
});

// 初始化
onMounted(() => {
  fetchMerchantList();
});
</script>

<style scoped>
.merchant-management {
  padding: 20px;
  height: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.list-card {
  margin-bottom: 20px;
}

.merchant-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.merchant-name {
  font-weight: bold;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.merchant-form {
  padding: 10px;
}

.form-section {
  margin-bottom: 30px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  padding-bottom: 20px;
}

.form-section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

.form-section-title i {
  margin-right: 8px;
}

.upload-tip {
  color: var(--el-text-color-secondary);
  font-size: 12px;
  margin-top: 5px;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.business-hours {
  display: flex;
  gap: 20px;
}

.action-buttons {
  text-align: center;
  padding: 20px 0;
}

.action-buttons button {
  margin: 0 10px;
}

.logo-uploader {
  width: 120px;
  height: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28px;
  color: var(--el-text-color-secondary);
}

.qualification-uploader :deep(.el-upload-list--picture-card) {
  --el-upload-list-picture-card-size: 148px;
}

/* 审核弹窗样式 */
.audit-dialog {
  margin-top: 20px;
}

.audit-content {
  padding: 20px 0;
}

.audit-content .merchant-info {
  margin-bottom: 30px;
}

.audit-radio-group {
  width: 100%;
  display: flex;
  gap: 12px;
  justify-content: center;
}

.audit-radio-group :deep(.el-radio-button__inner) {
  width: 160px;
  height: auto;
  padding: 16px 0;
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
}

.audit-radio-group :deep(.el-radio-button__inner):hover {
  border-color: var(--el-color-primary);
}

.audit-radio-group :deep(.el-radio-button__original) {
  opacity: 0;
  margin: 0;
}

.audit-radio-group :deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-radius: 8px;
}

.audit-radio-group :deep(.el-radio-button:last-child .el-radio-button__inner) {
  border-radius: 8px;
}

.audit-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.audit-icon {
  font-size: 24px;
}

.audit-icon.success {
  color: var(--el-color-success);
}

.audit-icon.danger {
  color: var(--el-color-danger);
}

.audit-dialog :deep(.el-dialog__body) {
  padding-top: 0;
  padding-bottom: 0;
}

.audit-dialog :deep(.el-dialog__header) {
  margin-right: 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.audit-dialog :deep(.el-dialog__footer) {
  border-top: 1px solid var(--el-border-color-lighter);
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 12px;
}

.empty-state {
  padding: 40px 0;
}

.empty-text {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
}

.empty-subtext {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  margin-top: 5px;
}

.mt-4 {
  margin-top: 16px;
}
</style>
